/**
 * Created by apple on 16/6/27.
 */
angular.module('starter.userService', ['starter.spmsLookupService'])
  .service('$user', function ($timeout, $q, $dfHttp, $dfDB) {
    var collection;

    var currentUser ;

    $timeout(function () {
      collectionDB(function () {
      });
    }, 300);

    function collectionDB(fn) {
      if (typeof(collection) == 'undefined') {
        $dfDB.collectionDB("userCollection").collectionSuccess(function (col) {
          collection = col;
          if (typeof(fn) == 'function') {
            return fn();
          }
        });
      } else {
        return fn();
      }
    };

    //
    function executeDBFunction(fn) {
      var deferred = $q.defer();
      var promise = deferred.promise;

      if (typeof(collection) == 'undefined') {
        $dfDB.collectionDB("userCollection").collectionSuccess(function (col) {
          collection = col;
          if (typeof(fn) == 'function') {
            deferred.resolve(fn());
          }
        });
      } else {
        deferred.resolve(fn());
      }

      promise.executeSuccess = function (fn) {
        promise.then(fn);
        return promise;
      };

      return promise;
    }

    //
    function executeDBFunctionSync(fn) {
      if (typeof(collection) == 'undefined') {
        $dfDB.collectionDB("userCollection").collectionSuccess(function (col) {
          collection = col;
          if (typeof(fn) == 'function') {
            return fn();
          }
        });
      } else {
        return fn();
      }
    }

    return {
      //用户登录
      loginUser: function (name, pw) {
        return $dfHttp.post("infor/user/userLogin.json", {'userPhone': name, 'password': pw});
      },

      // 获取验证码
      getSecurityCode: function (userPhone, businessType) {
        return $dfHttp.get("infor/user/getSecurityCode.json",{"userPhone": userPhone, "businessType": businessType})
      },

      // 重置密码
      resetPassword: function (userPhone, securityCode ,newPassword) {
        return $dfHttp.post("infor/user/resetPassWord.json",{"userPhone":userPhone, "securityCode":securityCode, "newPassword":newPassword})
      },

      saveUserWithoutAutoLogin: function (user) {
        angular.copy(user,currentUser) ;
        var saveFn = function () {
          var dbUserArray = collection.find({'userId': user.userId});
          if (dbUserArray.length == 0) {
            collection.insert(user);
          } else if (dbUserArray.length > 0) {
            angular.forEach(dbUserArray, function (dbUser) {
              user.$loki = dbUser.$loki ;
              collection.update(user);
            });
          }
          $dfDB.dbSave();
        }
        if (collection) {
          return executeDBFunctionSync(saveFn);
        } else {
          return executeDBFunction(saveFn);
        }
      },
      //lokijs
      saveUser: function (user) {
        angular.copy(user,currentUser) ;
        var saveFn = function () {
          collection.findAndUpdate(function (user) {
            return true;
          }, function (user) {
            user.autoLogin = false;
            collection.update(user);
          })

          var dbUserArray = collection.find({'userId': user.userId});
          if (dbUserArray || dbUserArray.length == 0) {
            user.RoleMember = JSON.stringify(user.RoleMember);
            user.providerAddresses = JSON.stringify(user.providerAddresses);
            user.regionCode = JSON.stringify(user.regionCode);
            // user.autoLogin = true;
            collection.insert(user);
          } else if (dbUserArray.length > 0) {
            angular.forEach(dbUserArray, function (dbUser) {
              angular.forEach(user, function (key, value) {
                dbUser[key] = value;
              });
              dbUser.autoLogin = user.autoLogin;
              dbUser.currentLogin = user.currentLogin ;
              collection.update(dbUser);
            });
          }
          $dfDB.dbSave();
        }
        if (collection) {
          return executeDBFunctionSync(saveFn);
        } else {
          return executeDBFunction(saveFn);
        }
      },

      getCurrentUser: function () {
        var getUserFn = function () {
          if (currentUser) {
            return currentUser ;
          } else {
            var currentUserArray = collection.find({'currentLogin': true});

            if(currentUserArray.length > 0) {
              var user = currentUserArray[0];
              if(angular.isString(user.RoleMember)){
                user.RoleMember = JSON.parse(user.RoleMember);
              }
              if(angular.isString(user.providerAddresses)){
                user.providerAddresses = JSON.parse(user.providerAddresses);
              }
              if(angular.isString(user.regionCode)){
                user.regionCode = JSON.parse(user.regionCode);
              }
              //stringify(user.RoleMember);
              //user.providerAddresses = JSON.stringify(user.providerAddresses);
              //user.regionCode = JSON.stringify(user.regionCode);
              return user;
            }
          }
          return {};
        }
        //if (collection) {
        //  return executeDBFunctionSync(getUserFn);
        //} else {
          return executeDBFunction(getUserFn);
        //}
      },

      getCurrentUserSync: function () {
        if (currentUser) {
          return currentUser ;
        } else {
          var collection = $dfDB.collectionDBSync('userCollection');
          var currentUserArray = collection.find({'currentLogin': true});
          if(currentUserArray.length > 0) {
            var user = currentUserArray[0];
            if(angular.isString(user.RoleMember)){
              user.RoleMember = JSON.parse(user.RoleMember);
            }
            if(angular.isString(user.providerAddresses)){
              user.providerAddresses = JSON.parse(user.providerAddresses);
            }
            if(angular.isString(user.regionCode)){
              user.regionCode = JSON.parse(user.regionCode);
            }
            //stringify(user.RoleMember);
            //user.providerAddresses = JSON.stringify(user.providerAddresses);
            //user.regionCode = JSON.stringify(user.regionCode);
            return user;
          }
        }
        return {};
      },

      clearUser : function () {
        var collection = $dfDB.collectionDBSync('userCollection');
        collection.clear();
        $dfDB.dbSave();
      }
   }
  })
